#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

namespace Client
{
    using namespace std;

    class udpClient
    {
    public:
        udpClient(const string& serverip,const uint16_t& serverport)
            :_serverip(serverip),_serverport(serverport),_sockfd(-1),_quit(false)
        {}
        void initClient()   //初始化客户端
        {
            // 1. 创建socket
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);
            if(_sockfd == -1)
            {
                cerr << "socket error: " << errno  << " : " << strerror(errno) << endl;
                exit(2);
            }
            cout << "socket success: " << " : " << _sockfd << endl;

            //2. client 要不要bind？必须要。需不需要程序员自己显示的bind？不需要。
            //  由操作系统自动形成port进行bind，那么OS在什么时候bind，如何bind？
        }
        //线程代码
        static void* readMessage(void* args)
        {
            int sockfd = *(static_cast<int*>(args));
            pthread_detach(pthread_self());

            while(true)
            {
                char buffer[1024];
                struct sockaddr_in temp;
                socklen_t temp_len = sizeof(temp);  //recvfrom: 从套接字接收消息
                ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&temp_len);
                if(n >= 0) buffer[n] = 0;
                // cout << "服务器翻译结果# " << buffer << endl;
                cout << buffer << endl;
            }
            return nullptr;
        }
        void run()      //运行客户端
        {   //让线程帮我们发送消息
            pthread_create(&_reader,nullptr,readMessage,(void*)&_sockfd);

            struct sockaddr_in server;
            memset(&server,0,sizeof(server)); //bzero和memset这两个都可以
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);

            string message;
            while(!_quit)
            {
                fprintf(stderr,"Please Enter# ");
                // cin >> message;
                getline(cin,message);
                // sendto :在套接字上发送消息
                sendto(_sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));

            }
        }
        ~udpClient()
        {}
    private:
        int _sockfd;    
        string _serverip;
        uint16_t _serverport;

        bool _quit;     //循环条件

        pthread_t _reader;
    };
} //namespace end Client
